import os
import jpype
jarpath = os.path.join(os.path.abspath('.'), 'SADK3.1.0.7-0.0.1.jar')

jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % jarpath)

FileInputStream = jpype.JClass("java.io.FileInputStream")
UnsupportedEncodingException = jpype.JClass("java.io.UnsupportedEncodingException")
Key = jpype.JClass("java.security.Key")
PrivateKey = jpype.JClass("java.security.PrivateKey")
PublicKey = jpype.JClass("java.security.PublicKey")
Mechanism = jpype.JClass("cfca.sm2rsa.common.Mechanism")
PKIException = jpype.JClass("cfca.sm2rsa.common.PKIException")

Base64 = jpype.JClass("cfca.util.Base64")
CertUtil = jpype.JClass("cfca.util.CertUtil")
EnvelopeUtil = jpype.JClass("cfca.util.EnvelopeUtil")
KeyUtil = jpype.JClass("cfca.util.KeyUtil")
SignatureUtil2 = jpype.JClass("cfca.util.SignatureUtil2")
JCrypto = jpype.JClass("cfca.util.cipher.lib.JCrypto")
Session = jpype.JClass("cfca.util.cipher.lib.Session")
X509Cert = jpype.JClass("cfca.x509.certificate.X509Cert")
X509CertHelper = jpype.JClass("cfca.x509.certificate.X509CertHelper")



class RsaUtil:

    JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, None)
    session = JCrypto.getInstance().openSession(JCrypto.JSOFT_LIB)

    def __init__(self, pfxPath, cerPath, pwd):
        self.priKey = KeyUtil.getPrivateKeyFromPFX(pfxPath, pwd)
        self.decert = CertUtil.getCertFromPfx(pfxPath, pwd)

        cert = X509CertHelper.parse(cerPath)
        self.pubKey = cert.getPublicKey()

        _is = FileInputStream(cerPath)
        self.encert = X509Cert(_is)

    def getRSAPriKey(self, pfxPath,pwd):
        priKey = KeyUtil.getPrivateKeyFromPFX(pfxPath, pwd)
        return priKey

    def getRSAPubKey(self, cerPath):
        cert = X509CertHelper.parse(cerPath)
        pubKey = cert.getPublicKey()
        return pubKey

    def rsaP1Sign(self, srcData):
        alg = Mechanism.SHA256_RSA
        signature = SignatureUtil2().p1SignMessage(alg, srcData.encode("utf-8"), self.priKey, self.session)
        return signature

    def rsaP1Verify(self, signData, srcData, cerPath):
        alg = Mechanism.SHA256_RSA
        ret = SignatureUtil2().p1VerifyMessage(alg, srcData.encode(), signData.encode(), self.pubKey, self.session)
        return ret

    def envelopMessage(self, srcData):
        # _is = FileInputStream(cerPath)
        # cert = X509Cert(_is)
        certs = [self.encert]
        encryptedData = EnvelopeUtil.envelopeMessage(srcData.encode("UTF-8"), Mechanism.DES3_CBC, certs)
        return encryptedData

    def openMessage(self, encryptedData):
        # priKey = KeyUtil.getPrivateKeyFromPFX(pfxPath, pfxPwd)
        # cert = CertUtil.getCertFromPfx(pfxPath, pfxPwd)
        sourceData = EnvelopeUtil.openEvelopedMessage(encryptedData.encode(), self.priKey, self.decert, self.session)
        return sourceData